<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Adv;
use App\Model\Advcontent;

class AdvContentController extends Controller
{
  // 获取广告内容列表
  public function getAdvContent()
  {
    $data = Advcontent::get();
    $data->each(function ($item) {
      $item->path = explode('|', $item->path);
      $item->advname = Adv::where('id', $item->advid)->value('name');
    });
    return response()->json(['status' => 200, 'data' => $data]);
  }

  // 根据id获取广告内容
  public function getAdvContentById($id)
  {
    $data = Advcontent::where('id', $id)->first();
    $data->path = explode('|', $data->path);
    return response()->json(['status' => 200, 'data' => $data]);
  }

  // 添加广告内容
  public function addAdvContent(Request $request)
  {
    $data = $request->all();
    // 判断添加的广告位是否存在
    $res = Advcontent::create([
      'advid' => $data['advid'],
      'path' => $data['path']
    ]);
    if (!$res) return response()->json(['status' => 400, 'msg' => '添加失败']);
    return response()->json(['status' => 200, 'msg' => '添加成功']);
  }

  // 根据id删除广告内容
  public function removeAdvContentById($id)
  {
    $res = Advcontent::where('id', $id)->delete();
    if (!$res) return response()->json(['status' => 400, 'msg' => '删除失败']);
    return response()->json(['status' => 200, 'msg' => '删除成功']);
  }

  // 根据id修改公告内容
  public function updateAdvContentById(Request $request, $id)
  {
    $data = $request->all();
    $res = Advcontent::where('id', $id)->update($data);
    if (!$res) return response()->json(['status' => 400, 'msg' => '修改失败']);
    return response()->json(['status' => 200, 'msg' => '修改成功']);
  }
}
